package com.streetlight.lampcursor.ui.status

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import com.lampcursor.streetlight.R
import com.lampcursor.streetlight.databinding.FragmentStatusBinding
import com.streetlight.lampcursor.model.StreetLightData

class StatusFragment : Fragment() {

    private var _binding: FragmentStatusBinding? = null
    private val binding get() = _binding!!
    
    private val viewModel: StatusViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        _binding = FragmentStatusBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        
        setupViews()
        setupObservers()
        setupClickListeners()
        
        // 初始加载数据
        viewModel.loadStatusData()
    }

    private fun setupViews() {
        // 初始化视图状态
        updateConnectionStatus(false)
    }

    private fun setupObservers() {
        viewModel.streetLightData.observe(viewLifecycleOwner) { data ->
            updateStatusData(data)
        }
        
        viewModel.isOnline.observe(viewLifecycleOwner) { isOnline ->
            updateConnectionStatus(isOnline)
        }
    }

    private fun setupClickListeners() {
        binding.btnRefresh.setOnClickListener {
            viewModel.loadStatusData()
        }
    }

    private fun updateConnectionStatus(isOnline: Boolean) {
        if (isOnline) {
            binding.viewConnectionStatus.setBackgroundResource(R.drawable.circle_status_online)
            binding.tvConnectionStatus.text = "在线"
        } else {
            binding.viewConnectionStatus.setBackgroundResource(R.drawable.circle_status_offline)
            binding.tvConnectionStatus.text = "离线"
        }
    }

    private fun updateStatusData(data: StreetLightData) {
        binding.tvPowerConsumption.text = "${data.powerConsumption} W"
        binding.tvWorkingHours.text = "${data.workingHours} 小时"
        binding.tvTemperature.text = "${data.temperature}°C"
        binding.tvVoltage.text = "${data.voltage}V"
        binding.tvCurrent.text = "${data.current}A"
        binding.tvBrightness.text = "${data.brightness}%"
        
        updateConnectionStatus(data.isOnline)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
} 